package com.thememaker.lockstyle.control;

import com.jfoenix.controls.JFXCheckBox;
import com.thememake.common.base.Strings;
import com.thememake.ui.Toast;
import com.thememaker.lockstyle.bean.ui.BaseView;
import com.thememaker.lockstyle.bean.ui.Image;
import com.thememaker.lockstyle.customview.EditItemHBox;
import com.thememaker.lockstyle.parsii.ExpressionUtils;
import com.thememaker.lockstyle.parsii.LockscreenViewPaesiiUtils;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Consumer;

public class ImageControl implements ILockscreenControl {
    private VBox vBox, editVBox;
    private EditItemHBox nameHBox, xHBox, yHBox, wHBox, hHBox;
    private JFXCheckBox alignCheckBox, alignVCheckBox;
    private ExpressionUtils expressionUtils;
    private Path imagePath = null, lockscreenPath;
    private int alpha = 255;
    private boolean selected = false;
    private JFXCheckBox adaptiveCheckBox;//= new JFXCheckBox();
    private Label warningLabel;
    private HBox adaptHbox;


    public Path getImagePath() {
        return imagePath;
    }

    @Override
    public Node initLockscreenControl(BaseView baseView, Path lockscreenPath, ExpressionUtils expressionUtils, Consumer<BaseView> consumer) {
        this.expressionUtils = expressionUtils;
        this.lockscreenPath = lockscreenPath;
        vBox = LayoutComponentUtils.getInstance().getControlView(600, 600);
        editVBox = initImageInfo((Image) baseView);
        vBox.getChildren().add(
                Optional.ofNullable(baseView)
                        .map(baseView1 -> getTitleNode(baseView1, consumer))
                        .orElse(LayoutComponentUtils.getInstance().getControlTitleLabel("新增图片组件"))
        );
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlNormalLabel("图片类型：" + (Strings.isNullOrEmpty(getImageType((Image) baseView)) ? "静态" : getImageType((Image) baseView))));
        nameHBox = EditItemHBox.initEditItem("组件名称", Optional.ofNullable(baseView).flatMap(baseView1 -> Optional.ofNullable(baseView1.getName())).orElse("default"), 200);
        nameHBox.setEditable(!Optional.ofNullable(baseView).isPresent());
        vBox.getChildren().add(nameHBox);
        HBox imageHbox = new HBox();
        imageHbox.setAlignment(Pos.CENTER_LEFT);
        String imagePathString = Optional.ofNullable(getImagePath(baseView, lockscreenPath)).map(Path::toString).orElse(null);
        imageHbox.getChildren().add(LayoutComponentUtils.getInstance().getControlNormalLabel("图片资源："));
        Label label = LayoutComponentUtils.getInstance().getControlNormalLabel(
                Optional.ofNullable(imagePathString).map(str -> "图片名称：" + Paths.get(str).getFileName().toString()).orElse("图片名称：您还未选择图片"));
        imageHbox.getChildren().add(LayoutComponentUtils.getInstance().getImagePane(lockscreenPath, 200, 200, imagePathString,
                0, 0, false, path -> {
                    imagePath = path;
                    Optional.ofNullable(baseView).map(baseView1 -> {
                        consumer.accept(baseView1);
                        return baseView1;
                    }).orElseGet(() -> {
                        String imageName = Optional.ofNullable(nameHBox.getEditValue())
                                .filter(str -> !str.trim().equals("default") && !str.trim().equals(""))
                                .map(String::trim).orElse(path.getFileName().toString().substring(0, path.getFileName().toString().lastIndexOf(".")));
                        nameHBox.setValue(imageName);
                        label.setText("图片名称：" + path.getFileName().toString());
                        return null;
                    });
//
                }));

        vBox.getChildren().add(imageHbox);
        vBox.getChildren().add(label);

        Optional.ofNullable(baseView).orElseGet(() -> {
            vBox.getChildren().add(editVBox);
            return null;
        });
        return vBox;
    }

    private Path getImagePath(BaseView baseView, Path lockscreenPath) {
        return LockscreenViewPaesiiUtils.getInstance(expressionUtils)
                .paesiiImagePath(Optional.ofNullable(baseView).map(baseView1 -> ((Image) baseView1)).orElse(null),
                        lockscreenPath.toString());
    }

    @Override
    public Node getCacheLockscreenControl() {
        return vBox;
    }

    @Override
    public void updateView() {
        updateCheck();
    }
    private void updateCheck(){
        if (LayoutComponentUtils.screen_heigth != 1920) {
            adaptiveCheckBox.setDisable(true);
            adaptHbox.getChildren().add(warningLabel);
        } else {
            adaptiveCheckBox.setDisable(false);
            adaptHbox.getChildren().remove(warningLabel);
        }
    }

//
//    public Node createNewControl(Path lockscreenPath, ExpressionUtils expressionUtils, Consumer<BaseView> consumer){
//
//        return vBox;
//    }

    private Node getTitleNode(BaseView baseView, Consumer<BaseView> consumer) {
        return LayoutComponentUtils.getInstance().getEditTitleHbox("图片组件",
                (editButton, saveButton) -> {
                    editButton.setVisible(false);
                    saveButton.setVisible(true);
                    nameHBox.setEditable(true);
                    vBox.getChildren().add(editVBox);
                },
                (editButton, saveButton) -> Optional.of(saveImageInfo((Image) baseView))
                        .filter(canSave -> canSave)
                        .map(canSave -> {
//                            BaseView baseView1 = moreResolutionRatio(baseView);
                            baseView.setFitFX(selected);
                            editButton.setVisible(true);
                            saveButton.setVisible(false);
                            nameHBox.setEditable(false);
                            vBox.getChildren().remove(editVBox);
                            consumer.accept(baseView);
                            return true;
                        }));
    }


    private String getImageType(Image image) {
        StringBuffer imageType = new StringBuffer();
        return Optional.ofNullable(image).map(image1 -> {
            Optional.ofNullable(image.getSourcesAnimation()).ifPresent(sourcesAnimation -> imageType.append("序列帧 "));
            Optional.ofNullable(image.getPositionAnimation()).ifPresent(sourcesAnimation -> imageType.append("位移 "));
            Optional.ofNullable(image.getAlphaAnimation()).ifPresent(sourcesAnimation -> imageType.append("渐隐 "));
            Optional.ofNullable(image.getRotationAnimation()).ifPresent(sourcesAnimation -> imageType.append("旋转 "));
            Optional.ofNullable(image.getSizeAnimation()).ifPresent(sourcesAnimation -> imageType.append("缩放 "));
            return imageType.toString();
        }).orElse(imageType.toString());
    }

    private VBox initImageInfo(Image image) {
        VBox vBox = new VBox();
        vBox.setSpacing(10);
        adaptiveCheckBox = new JFXCheckBox();
        adaptiveCheckBox.setId("fit-more");
        adaptHbox = new HBox();
        HBox.setMargin(adaptiveCheckBox, new Insets(2, 0, 0, 10));
        adaptHbox.getChildren().add(LayoutComponentUtils.getInstance().getControlTitleLabel("屏幕高度适配 :"));
        adaptiveCheckBox.setSelected(Optional.ofNullable(image)
                .map(img -> Optional.ofNullable(image.getFitFX()).orElse(false))
                .orElse(false));
        selected = adaptiveCheckBox.isSelected();
//        if (image != null) {
//            int res = image.getY().indexOf("#screen_height-1920+");
//            if (res != -1) {
//                adaptiveCheckBox.setSelected(true);
//                selected = true;
//            }
//        }

        warningLabel = LayoutComponentUtils.getInstance().getControlTitleLabel("(请到1080*1920分辨率适配)");
        adaptHbox.getChildren().add(adaptiveCheckBox);
        updateCheck();
        if (image != null) {
            vBox.getChildren().add(adaptHbox);
        }

        adaptiveCheckBox.selectedProperty().addListener((obj, oldValue, newValue) -> {
            selected = newValue;
        });
//        adaptiveCheckBox.setOnAction(event -> {
//            if (adaptiveCheckBox.isSelected()) {
//                selected = true;
//                adaptiveCheckBox.setSelected(true);
//                System.out.println("适配的高度===========" + image.getY());
//            } else {
//                selected = false;
//                adaptiveCheckBox.setSelected(false);
//            }
//        });
        System.err.println("是否选中：：：" + adaptiveCheckBox.isSelected());
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlTitleLabel("位置信息："));
        xHBox = EditItemHBox.initEditItem("X坐标 ", Optional.ofNullable(image).map(image1 -> checkEditString(image1.getX())).orElse(""), 200);
        yHBox = EditItemHBox.initEditItem("Y坐标 ", Optional.ofNullable(image).map(image1 -> checkEditString(image1.getY())).orElse(""), 200);
        wHBox = EditItemHBox.initEditItem("宽 度 ", Optional.ofNullable(image).map(image1 -> checkEditString(image1.getW())).orElse(""), 200);
        hHBox = EditItemHBox.initEditItem("高 度 ", Optional.ofNullable(image).map(image1 -> checkEditString(image1.getH())).orElse(""), 200);
        xHBox.addEditCheck(expressionUtils, 1000);
        yHBox.addEditCheck(expressionUtils, 1000);
        wHBox.addEditCheck(expressionUtils, 1000);
        hHBox.addEditCheck(expressionUtils, 1000);
        HBox xyHBox = new HBox();
        xyHBox.setSpacing(20);
        xyHBox.getChildren().addAll(xHBox, wHBox);
        HBox whHBox = new HBox();
        whHBox.setSpacing(20);
        whHBox.getChildren().addAll(yHBox, hHBox);
        vBox.getChildren().addAll(xyHBox, whHBox);
//        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlTitleLabel("对齐方式："));

        HBox alignHBox = new HBox();
        alignHBox.setSpacing(20);

        alignCheckBox = LayoutComponentUtils.getInstance().getCheckBox("水平居中");
        alignCheckBox.setSelected(Optional.ofNullable(image).map(image1 -> Optional.ofNullable(image1.getAlign()))
                .map(s -> s.equals("center")).orElse(false));

        alignVCheckBox = LayoutComponentUtils.getInstance().getCheckBox("垂直居中");
        alignVCheckBox.setSelected(Optional.ofNullable(image).map(image1 -> Optional.ofNullable(image1.getAlignV()))
                .map(s -> s.equals("center")).orElse(false));

//        alignHBox.getChildren().add(alignCheckBox);
//        alignHBox.getChildren().add(alignVCheckBox);
        vBox.getChildren().add(alignHBox);
        alpha = Optional.ofNullable(image).flatMap(image1 -> Optional.ofNullable(image1.getAlpha())).map(s -> (int) (expressionUtils.parseExpr(s) * 100d / 255d)).orElse(100);

        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlTitleLabel("图片透明度："));
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getSlideBarHbox("透明度",
                alpha, 0, 100, (observable, oldValue, newValue) -> {
                    alpha = newValue.intValue();
                }));
        return vBox;
    }


    private String checkEditString(String value) {
        return Optional.ofNullable(value).map(s -> ((int) expressionUtils.parseExpr(value) + "")).orElse("");
    }

    private boolean saveImageInfo(Image image) {
        boolean test = Optional.of(nameHBox.isError())
                .filter(isError -> !isError)
                .map(b -> xHBox.isError())
                .filter(isError -> !isError)
                .map(b -> yHBox.isError())
                .filter(isError -> !isError)
                .map(b -> wHBox.isError())
                .filter(isError -> !isError)
                .map(b -> hHBox.isError())
                .filter(isError -> !isError)
                .map(isError -> {
                    image.setName(Optional.ofNullable(nameHBox.getEditValue()).filter(name -> !name.equals("default")).orElse(null));
                    image.setX(Optional.ofNullable(xHBox.getEditValue()).filter(x -> !x.trim().equals(""))
                            .map(str -> LockstyleShowRightEventControl.splitXYValue(image.getX()) + str).orElse("0"));
                    image.setY(Optional.ofNullable(yHBox.getEditValue()).filter(y -> !y.trim().equals(""))
                            .map(str -> LockstyleShowRightEventControl.splitXYValue(image.getY()) + str).orElse("0"));
                    image.setW(Optional.ofNullable(wHBox.getEditValue()).filter(w -> !w.trim().equals("") && expressionUtils.parseExpr(w) > 0)
                            .map(str -> LockstyleShowRightEventControl.splitXYValue(image.getW()) + str).orElse(null));
                    image.setH(Optional.ofNullable(hHBox.getEditValue()).filter(h -> !h.trim().equals("") && expressionUtils.parseExpr(h) > 0)
                            .map(str -> LockstyleShowRightEventControl.splitXYValue(image.getH()) + str).orElse(null));
                    image.setAlign(Optional.of(alignCheckBox.isSelected()).filter(selected -> selected).map(selected -> "center").orElse(null));
                    image.setAlignV(Optional.of(alignVCheckBox.isSelected()).filter(selected -> selected).map(selected -> "center").orElse(null));
                    image.setAlpha(Optional.of(alpha).filter(alpha -> alpha != 100)
                            .map(alpha -> LockstyleShowRightEventControl.splitXYValue(image.getAlpha()) + (int) (alpha * 2.55d)).orElse(null));
                    return true;
                }).orElse(false);
        return test;
    }

    public BaseView getCreateView() {
        Image image = new Image();
        if (imagePath == null) {
            Toast.makeText(new Stage(), "您还未选择图片", 1000);
            return null;
        }
        if (xHBox.isError()) {
            Toast.makeText(new Stage(), "坐标X输入有误", 1000);
            return null;
        }
        if (yHBox.isError()) {
            Toast.makeText(new Stage(), "坐标Y输入有误", 1000);
            return null;
        }
        if (wHBox.isError()) {
            Toast.makeText(new Stage(), "宽度输入有误", 1000);
            return null;
        }
        if (hHBox.isError()) {
            Toast.makeText(new Stage(), "高度输入有误", 1000);
            return null;
        }
        image.setSrc(imagePath.toString()
                .replace(lockscreenPath.toString() + File.separator, "").replace(File.separator, "/"));
        saveImageInfo(image);
        image.setName(Optional.ofNullable(nameHBox.getEditValue())
                .filter(str -> !str.equals("default") && !str.equals("")).orElse(null));
        return image;
    }

//    private BaseView moreResolutionRatio(BaseView baseView) {
//        if (selected) {
//            int screenH = LayoutComponentUtils.screen_heigth - 1920;
//            int height = Integer.parseInt(baseView.getY()) - screenH;
//            baseView.setY(height + "");
//        }
//        if (adaptiveCheckBox.isSelected()) {
//            String valueY = "#screen_height-1920+" + baseView.getY();
//            baseView.setY(valueY);
//        } else {
//            baseView.setY(baseView.getY().replace("#screen_height-1920+", ""));
//        }
//        System.out.println("出去的：》》》" + JSON.toJSONString(baseView));
//        return baseView;
//
//    }

}
